/**
 * Author : Fengyuan(Franklin) Zhang
 * Date : 2019/3/6
 * Description : model service control
 */

var request = require('request');
var Setting = require('../setting');

var ModelServiceCtrl = function () {};

module.exports = ModelServiceCtrl;

ModelServiceCtrl.refreshModelServicesData = function (callback) {
    request('http://' + Setting.binding.ip + ':' + Setting.binding.port.toString() + '/server/modelser/all', function (err, response, body) {
        if(err){
            return callback(err);
        }
        var resJson = JSON.parse(body);
        if(resJson.result == 'err'){
          return callback(new Error("Error in getting model : " + resJson.message));
        }
        global.data_cache = resJson.data;
        return callback(null, true);
      });
}

ModelServiceCtrl.getModelServiceByPID = function (pid, callback) {
    if(global.data_cache){
        for(var i = 0; i < global.data_cache.length; i++){
          if(global.data_cache[i]._id == pid){
            return callback(null, global.data_cache[i]);
          }
        }
        return callback(null, null);
      }
      else{
          ModelServiceCtrl.refreshModelServicesData(function(err, result){
              if(err){
                  return callback(err);
              }
              ModelServiceCtrl.getModelServiceByPID(pid, function (err, ms) {
                  return callback(err, ms);
              });
          });
      }
}

ModelServiceCtrl.postTask = function (option, callback) {
    //！ TODO post a task
}